#include "form_livingroom.h"
#include "ui_form_livingroom.h"

int num1=1, num2=1, num3=1,key[11];
QString str,val[11];
QMQTT::Message msg1,msg2,msg3;

Form_livingroom::Form_livingroom(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_livingroom)
{
    ui->setupUi(this);
    qDebug()<<"test->Livingroom";

    QPixmap img(":/new/prefix1/pictures/livingroom.jpeg");
    ui->label_img->setPixmap(img);

    connect(ui->pushButton_livingroom,SIGNAL(clicked()),this,SLOT(clickedLivingroomBtn()));
    connect(ui->pushButton_bedroom,SIGNAL(clicked()),this,SLOT(clickedBedroomBtn()));
    connect(ui->pushButton_scene,SIGNAL(clicked()),this,SLOT(clickedSceneBtn()));
    connect(ui->pushButton_set,SIGNAL(clicked()),this,SLOT(clickedSetBtn()));
    connect(ui->pushButton_noact,SIGNAL(clicked()),this,SLOT(clickedNoact()));
    connect(ui->pushButton_change,SIGNAL(clicked()),this,SLOT(clickedChange()));
    connect(ui->pushButton_time,SIGNAL(clicked()),this,SLOT(clickedTime()));
    //按钮设置颜色
    ui->pushButton_temperature->setIcon(QIcon(":/new/prefix1/pictures/温度计.png"));
    ui->pushButton_temperature->setIconSize(QSize(60,60));
    ui->pushButton_humidity->setIcon(QIcon(":/new/prefix1/pictures/湿度.png"));
    ui->pushButton_humidity->setIconSize(QSize(60,60));
    ui->pushButton_ill->setIcon(QIcon(":/new/prefix1/pictures/太阳.png"));
    ui->pushButton_ill->setIconSize(QSize(60,60));
    ui->pushButton_light->setIcon(QIcon(":/new/prefix1/pictures/灯.png"));
    ui->pushButton_light->setIconSize(QSize(60,60));
    ui->pushButton_alarm->setIcon(QIcon(":/new/prefix1/pictures/3.1铃铛.png"));
    ui->pushButton_alarm->setIconSize(QSize(60,60));
    ui->pushButton_fan->setIcon(QIcon(":/new/prefix1/pictures/通风风扇.png"));
    ui->pushButton_fan->setIconSize(QSize(60,60));
    //左侧按钮栏初始化
    ui->pushButton_livingroom->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_bedroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_scene->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_set->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_noact->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_change->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_time->setStyleSheet(QPushButton_STYTLE_OFF);

    connect(ui->pushButton_temperature,SIGNAL(clicked()),this,SLOT(collectTemprature()));
    connect(ui->pushButton_humidity,SIGNAL(clicked()),this,SLOT(collectHumidity()));
    connect(ui->pushButton_ill,SIGNAL(clicked()),this,SLOT(collectIll()));
    connect(ui->pushButton_light,SIGNAL(clicked()),this,SLOT(controlLight()));
    connect(ui->pushButton_alarm,SIGNAL(clicked()),this,SLOT(controlAlarm()));
    connect(ui->pushButton_fan,SIGNAL(clicked()),this,SLOT(controlFan()));

}

void Form_livingroom::connectServer()
{
    client = new QMQTT::Client(QHostAddress("192.168.31.161"),1883);
    client->setClientId("clientid");
    client->connectToHost();
    connect(client,SIGNAL(connected()),this,SLOT(doConnected()));
    connect(client,SIGNAL(subscribed(const QString&, const quint8)),this,SLOT(doSubscribed(const QString&, const quint8)));
    connect(client,SIGNAL(received(QMQTT::Message)),this,SLOT(doDataReceived(QMQTT::Message)));
}

void Form_livingroom::doConnected()//连接成功
{
    qDebug()<<"doConnected";
    client->subscribe("/app/data/up");//订阅"up"主题
//    client->subscribe("/app/control/up");
//    client->subscribe("/app/mode/up");

}

void Form_livingroom::doSubscribed(const QString& topic, const quint8 qos)//订阅成功
{
    qDebug()<<"doSubscribed = "<<topic;

}

void Form_livingroom::doDataReceived(QMQTT::Message message)//接收数据
{
    QString mes = QString(message.id())+" "+QString(message.qos())+" "+message.topic()+" "+message.payload()+"\n";
    str = message.payload();
    qDebug()<<"mes="<<str;
//    keyJudge();
    dataJsonDeserialization();
//    controlJsonDeserialization();
//    modeJsonDeserialization();
}

void Form_livingroom::dataJsonDeserialization()//数据查询Json反序列化
{
    QJsonParseError jsonError;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(str.toLatin1(),&jsonError));
    if(jsonError.error == QJsonParseError::NoError)
    {
        if(jsonDoc.isObject())
        {
            QJsonObject obj = jsonDoc.object();
            if(obj.contains("type"))
            {
                qDebug() << "type : " << obj["type"].toInt();
            }
            if(obj.contains("result"))
            {
                qDebug() << "result :" << obj["result"].toInt();
            }
            if(obj.contains("data"))
            {
                QJsonArray array = obj.value("data").toArray();
                for(int i = 0;i<array.size();i++)
                {
                    QJsonObject array_data = array.at(i).toObject();
                    qDebug() << "key : " << array_data.value("key").toInt();
                    qDebug() << "val : " << array_data.value("val").toInt();
                    if(array_data.contains("key"))
                    {
                        QJsonValue key_value = array_data.take("key");
                        if(key_value.isDouble())
                        {
                            key[i] = key_value.toVariant().toInt();
                        }
                    }
                    if(array_data.contains("val"))
                    {
                        QJsonValue value = array_data.take("val");
                        if(value.isString())
                        {
                            val[i] = value.toVariant().toString();
                        }
                    }
                }

            }
        }
    }
    else
    {
        qDebug() << "json error" << jsonError.errorString();
        return;
    }
    for(int j = 0;j<11;j++)
    {
        qDebug() << "QT解析出来的key值为:" << key[j] << "val值:" << val[j];
    }
}

//void Form_livingroom::keyJudge()
//{
//    switch (*key) {
//    case 1:
//        client->subscribe("/app/data/up");
//        collectTemprature();
//        break;
//    case 2:
//        client->subscribe("/app/data/up");
//        collectHumidity();
//        break;
//    case 3:
//        client->subscribe("/app/data/up");
//        collectIll();
//        break;
//    case 4:
//        client->subscribe("/app/control/up");
//        controlLight();
//        break;
//    case 5:
//        client->subscribe("/app/control/up");
//        controlAlarm();
//        break;
//    case 6:
//        client->subscribe("/app/control/up");
//        controlFan();
//        break;
//    default:
//        break;
//    }
//}

void Form_livingroom::collectTemprature()//采集温度
{
    client->subscribe("/app/data/up");
    QMQTT::Message message;
    message.setTopic("/app/data/down");//设置主题
    client->publish(message);//发布主题
    qDebug()<<"doPulished = "<<message.topic();
    qDebug() << val[0];
    qDebug() << key[0];
    ui->label_tep->setText(val[0].append("℃"));
}

void Form_livingroom::collectHumidity()//采集湿度
{
    client->subscribe("/app/data/up");
    QMQTT::Message message;
    message.setTopic("/app/data/down");
    client->publish(message);
    qDebug()<<"doPulished = "<<message.topic();
    qDebug() << val[1];
    qDebug() << key[1];
    ui->label_hum->setText(val[1].append("%"));
}

void Form_livingroom::collectIll()//采集光强
{
    client->subscribe("/app/data/up");
    QMQTT::Message message;
    message.setTopic("/app/data/down");
    client->publish(message);
    qDebug()<<"doPulished = "<<message.topic();
    qDebug() << val[2];
    qDebug() << key[2];
    ui->label_ill->setText(val[2].append("Lux"));
}

void Form_livingroom::controlJsonDeserialization()//控制协议Json反序列化
{
    QJsonParseError jsonError;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(str.toLatin1(),&jsonError));
    if(jsonError.error == QJsonParseError::NoError)
    {
        if(jsonDoc.isObject())
        {
            QJsonObject obj = jsonDoc.object();
            if(obj.contains("type"))
            {
                qDebug() << "type : " << obj["type"].toInt();
            }
            if(obj.contains("result"))
            {
                qDebug() << "result :" << obj["result"].toInt();
            }
            if(obj.contains("msg"))
            {
                qDebug() << "msg : " << obj["msg"].toString();
            }
        }
    }  
}

void Form_livingroom::controlLight()//控制客厅灯
{
    client->subscribe("/app/control/up");

    QJsonObject control_obj,item_obj;
    item_obj.insert("val",QString::number(num1%2));
    item_obj.insert("key",4);
    control_obj.insert("data",item_obj);
    control_obj.insert("type",2);
    QJsonDocument control_doc;
    control_doc.setObject(control_obj);
    QByteArray control_array = control_doc.toJson(QJsonDocument::Compact);
    QString control_str = control_array;

    QMQTT::Message message;
    message.setTopic("/app/control/down");
    message.setPayload(control_str.toLocal8Bit());
    client->publish(message); 
    qDebug() << "doPublished = " << message.topic();
    qDebug() << control_str;
    if(num1%2 == 0)
    {
        ui->label_light->setText("  客厅灯|关");
    }
    else
    {
        ui->label_light->setText("  客厅灯|开");
    }
    num1++;
}

void Form_livingroom::controlAlarm()//控制烟雾报警器
{
    client->subscribe("/app/control/up");

    QJsonObject control_obj,item_obj;
    item_obj.insert("val",QString::number(num2%2));
    item_obj.insert("key",5);
    control_obj.insert("data",item_obj);
    control_obj.insert("type",2);
    QJsonDocument control_doc;
    control_doc.setObject(control_obj);
    QByteArray control_array = control_doc.toJson(QJsonDocument::Compact);
    QString control_str = control_array;

    QMQTT::Message message;
    message.setTopic("/app/control/down");
    message.setPayload(control_str.toLocal8Bit());
    client->publish(message);
    qDebug() << "doPublished = " << message.topic();
    qDebug() << control_str;
//    if(num2%2 == 0)
//    {
//        ui->label_alarm->setText("烟雾报警");
//    }
//    else
//    {
//        ui->label_alarm->setText("烟雾报警");
//    }
    num2++;
}

void Form_livingroom::controlFan()//控制风扇
{
    client->subscribe("/app/control/up");

    QJsonObject control_obj,item_obj;
    item_obj.insert("val",QString::number(num3%4));
    item_obj.insert("key",6);
    control_obj.insert("data",item_obj);
    control_obj.insert("type",2);
    QJsonDocument control_doc;
    control_doc.setObject(control_obj);
    QByteArray control_array = control_doc.toJson(QJsonDocument::Compact);
    QString control_str = control_array;

    QMQTT::Message message;
    message.setTopic("/app/control/down");
    message.setPayload(control_str.toLocal8Bit());
    client->publish(message);
    qDebug() << "doPublished = " << message.topic();
    qDebug() << control_str;
    if(num3%4 == 0)
    {
        ui->label_fan->setText("风扇|关");
    }
    else if(num3%4 == 1)
    {
        ui->label_fan->setText("风扇|一档");
    }
    else if(num3%4 == 2)
    {
        ui->label_fan->setText("风扇|二档");
    }
    else
    {
        ui->label_fan->setText("风扇|三档");
    }
    num3++;
}

QString Form_livingroom::modeJsonSerialization(int type_m)//模式修改Json序列化
{
    QString mode_str;
    QJsonObject mode_obj,item_obj;
    item_obj.insert("period",5);
    item_obj.insert("type",type_m);
    mode_obj.insert("data",item_obj);
    QJsonDocument mode_doc;
    mode_doc.setObject(mode_obj);
    QByteArray mode_array = mode_doc.toJson(QJsonDocument::Compact);
    mode_str = mode_array;

    return mode_str;
}

void Form_livingroom::modeJsonDeserialization()//模式修改Json反序列化
{
    QJsonParseError jsonError;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(str.toLatin1(),&jsonError));
    if(jsonError.error == QJsonParseError::NoError)
    {
        if(jsonDoc.isObject())
        {
            QJsonObject obj = jsonDoc.object();
            if(obj.contains("result"))
            {
                qDebug() << "result :" << obj["result"].toInt();
            }
            if(obj.contains("msg"))
            {
                qDebug() << "msg : " << obj["msg"].toString();
            }
        }
    }
}

//上报模式修改信号槽
void Form_livingroom::clickedNoact()
{
    ui->pushButton_noact->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_change->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_time->setStyleSheet(QPushButton_STYTLE_OFF);

    QString mode_str(modeJsonSerialization(0));
    QMQTT::Message message;
    message.setTopic("/app/mode/down");
    message.setPayload(mode_str.toLocal8Bit());
    client->publish(message);
    qDebug() << "dePublished = " << message.topic();
    qDebug() << mode_str;
}

void Form_livingroom::clickedChange()
{
    ui->pushButton_noact->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_change->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_time->setStyleSheet(QPushButton_STYTLE_OFF);

    QString mode_str(modeJsonSerialization(1));
    QMQTT::Message message;
    message.setTopic("/app/mode/down");
    message.setPayload(mode_str.toLocal8Bit());
    client->publish(message);
    qDebug() << "dePublished = " << message.topic();
    qDebug() << mode_str;
}

void Form_livingroom::clickedTime()
{
    ui->pushButton_noact->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_change->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_time->setStyleSheet(QPushButton_STYTLE_ON);

    QString mode_str(modeJsonSerialization(2));
    QMQTT::Message message;
    message.setTopic("/app/mode/down");
    message.setPayload(mode_str.toLocal8Bit());
    client->publish(message);
    qDebug() << "dePublished = " << message.topic();
    qDebug() << mode_str;
}

//界面切换四个槽函数
void Form_livingroom::clickedLivingroomBtn()
{
    ui->pushButton_livingroom->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_bedroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_scene->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_set->setStyleSheet(QPushButton_STYTLE_OFF);
}

void Form_livingroom::clickedBedroomBtn()
{
    ui->pushButton_bedroom->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_livingroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_scene->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_set->setStyleSheet(QPushButton_STYTLE_OFF);

    Form_bedroom *br = new Form_bedroom;
    br->connectServer();
    this->hide();
    br->show();
}

void Form_livingroom::clickedSceneBtn()
{
    ui->pushButton_scene->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_livingroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_bedroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_set->setStyleSheet(QPushButton_STYTLE_OFF);

    Form_scene *sce = new Form_scene;
    this->hide();
    sce->show();
}

void Form_livingroom::clickedSetBtn()
{
    ui->pushButton_set->setStyleSheet(QPushButton_STYTLE_ON);
    ui->pushButton_livingroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_bedroom->setStyleSheet(QPushButton_STYTLE_OFF);
    ui->pushButton_scene->setStyleSheet(QPushButton_STYTLE_OFF);

    Form_set *set = new Form_set;
    this->hide();
    set->show();
}

Form_livingroom::~Form_livingroom()
{
    delete ui;
}

